<template>
	<view class="content">
		<!-- 模糊背景 -->
		<img class="bgfilter" src="https://lesson.iapeap.com/seleepbg.png" alt="" />
		<!-- 内容盒子 -->
		<view class="box">
			<!-- 导航 -->
			<view class="navigateBack">
				<img src="https://lesson.iapeap.com/gobake.png" alt="" style="width: 50rpx; height: 50rpx;"
					@click="gobake" />
				<view class="navigationTitle">
					答题测试
				</view>
				<img src="https://lesson.iapeap.com/home.png" alt="" style="width: 50rpx; height: 50rpx;" />
			</view>

			<!-- 页面内容⬇️ -->
			<view class="answer_timu">
				<view class="timu_title">
					<view class="">
						答题进度
					</view>
					<view class="">
						{{currentQuestionIndex + 1}}/{{subjectList.length}}
					</view>
				</view>
				<view class="slider">
					<van-slider :value="currentQuestionIndex" :min="0" :max="subjectList.length - 1"
						active-color="#79B0F5" bar-height="10px" />
				</view>
			</view>
			<img class="suozhen" src="https://lesson.iapeap.com/suozhen.png" alt="" />

			<view class="answer_daan">
				<template v-if="currentQuestion">
					<view class="xiaobiaoti">
						{{currentQuestion.subject}}
					</view>

					<view class="options" v-for="(item, index) in currentQuestion.item" :key="index">
						<view class="options_item" @click="selectOption(index,item)"
							:class="{ 'options_item2': isSelected(index), 'options_item3': showNext && isSelected(index) }">
							{{item.name}}
						</view>
					</view>
					<img class="optionscat" src="https://lesson.iapeap.com/images/sleep/testcat.png" alt="" />
				</template>
			</view>

			<view class="test_btn">
				<!-- 上一题 -->
				<img class="btnimg" src="https://lesson.iapeap.com/images/sleep/shangyiti.png" alt=""
					@click="prevQuestion" :disabled="currentQuestionIndex == 0" v-if="currentQuestionIndex >= 1" />
				<!-- 下一题 -->
				<!-- 				<img class="btnimg" src="https://lesson.iapeap.com/images/sleep/xiayiti.png" alt=""
					@click="nextQuestion" v-if="currentQuestionIndex < subjectList.length - 1" /> -->
				<!-- 提交 -->
				<img class="btnimg" src="https://lesson.iapeap.com/images/sleep/tijiao.png" alt="" @click="submit"
					v-if="currentQuestionIndex === subjectList.length - 1" />
			</view>
		</view>

		<!-- 弹窗 -->
		<view class="tjcg" v-if="showsubmit">
			<view class="tjimg">
				<view class="gobaogao" @click="gobaogao"></view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getQuestionList,
		saveAnswer,
	} from "../../utils/getDate.js";
	export default {
		data() {
			return {
				starttime: "", // 进入页面时间
				endtime: "", // 退出页面时间
				time: 0, // 页面累积时间
				subjectId: "",
				reportId: "",
				subjectList: [], // 题目列表
				currentQuestionIndex: 0,
				selectedOptions: [], // 存储每个题目的选择
				showNext: false,
				answer: [],
				showsubmit: false,
				canSelect: true, // 控制是否允许选择
				timer: null, // 定时器
				storageKey: "answerProgressData", // 本地存储的key
				starttime: "",
			}
		},
		computed: {
			currentQuestion() {
				return this.subjectList[this.currentQuestionIndex];
			}
		},
		onLoad() {
			this.ongetQuestionList();
			// 页面加载时尝试恢复保存的答题进度
			this.restoreProgress();
			// 获取当前时间
			this.getCurrentDateTime();

		},
		onShow() {
		},
		onUnload() {},
		onHide() {
			// 页面隐藏时保存进度
			this.saveProgress();
		},
		methods: {
			getCurrentDateTime() {
				const date = new Date();
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份补0
				const day = String(date.getDate()).padStart(2, '0');
				const hour = String(date.getHours()).padStart(2, '0');
				const minute = String(date.getMinutes()).padStart(2, '0');
				const second = String(date.getSeconds()).padStart(2, '0');

				this.starttime = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
				console.log("当前时间：", this.starttime);
			},
			gobaogao() {
				// 提交成功后清除缓存
				this.clearProgress();
				uni.navigateTo({
					url: `/subPackages/pages2/test/Report14?subjectId=${this.subjectId}`
				})
			},
			// 保存答题进度到本地存储
			saveProgress() {
				try {
					const progressData = {
						currentQuestionIndex: this.currentQuestionIndex,
						selectedOptions: this.selectedOptions,
						answer: this.answer,
						subjectList: this.subjectList, // 如果需要离线答题可以保存题目
						saveTime: new Date().getTime()
					};
					uni.setStorageSync(this.storageKey, progressData);
					console.log("答题进度已保存");
				} catch (e) {
					console.error("保存答题进度失败:", e);
				}
			},
			// 从本地存储恢复答题进度
			restoreProgress() {
				try {
					const progressData = uni.getStorageSync(this.storageKey);
					if (progressData) {
						// 检查数据是否过期（例如超过24小时）
						const currentTime = new Date().getTime();
						const saveTime = progressData.saveTime || 0;
						const isExpired = (currentTime - saveTime) > 24 * 60 * 60 * 1000;

						if (!isExpired) {
							this.currentQuestionIndex = progressData.currentQuestionIndex || 0;
							this.selectedOptions = progressData.selectedOptions || [];
							this.answer = progressData.answer || [];
							console.log("答题进度已恢复");
						} else {
							// 数据过期，清除
							this.clearProgress();
							console.log("保存的答题进度已过期，已清除");
						}
					}
				} catch (e) {
					console.error("恢复答题进度失败:", e);
				}
			},
			// 清除保存的答题进度
			clearProgress() {
				try {
					uni.removeStorageSync(this.storageKey);
					console.log("答题进度已清除");
				} catch (e) {
					console.error("清除答题进度失败:", e);
				}
			},
			ongetQuestionList() {
				uni.showLoading({
					title: "获取题目...",

				})
				getQuestionList().then(res => {
					if (res.state = "ok") {
						uni.hideLoading()
					}
					const transformPart = (partData) => {
						if (!partData) return [];
						return partData.map(item => {
							let options = [];

							if (item.item && item.item.value) {
								options = item.item.value.map((opt, idx) => ({
									id: item.id,
									name: opt,
									subjectid: item.id
								}));
							} else if (item.value) {
								options = item.value.map((opt, idx) => ({
									id: item.id,
									name: opt,
									subjectid: item.id
								}));
							}

							return {
								id: item.id,
								subject: item.subject,
								type: item.type,
								part: item.part,
								item: options
							};
						});
					};

					// 合并所有部分
					this.subjectList = [
						...res.data.part1,
						...res.data.part2,
						...res.data.part3,
						...res.data.part4,
						...transformPart(res.data.part5),
						...transformPart(res.data.part6)
					];

					console.log("题目列表:", this.subjectList);

					// 获取题目后再次尝试恢复进度（确保题目加载完成）
					this.$nextTick(() => {
						this.restoreProgress();
					});
				})
			},
			nextQuestion() {
				if (this.currentQuestionIndex < this.subjectList.length - 1) {
					this.currentQuestionIndex++;
					this.showNext = false;
					// 切换题目后保存进度
					this.saveProgress();
				}
			},
			prevQuestion() {
				if (this.currentQuestionIndex > 0) {
					this.clearCurrentSelection();
					this.currentQuestionIndex--;
					this.showNext = false;
					// 切换题目后保存进度
					this.saveProgress();
				}
			},
			selectOption(optionIndex, item) {
				if (!this.canSelect) return; // 如果不能选择，则直接返回

				if (!this.selectedOptions[this.currentQuestionIndex]) {
					this.$set(this.selectedOptions, this.currentQuestionIndex, []);
				}
				// 清除上一次选择的题目样式
				if (this.selectedOptions[this.currentQuestionIndex].length > 0) {
					this.selectedOptions[this.currentQuestionIndex] = [];
				}
				const options = this.selectedOptions[this.currentQuestionIndex];
				if (!options.includes(optionIndex)) {
					options.push(optionIndex);
				}
				this.showNext = true;

				// 记录答案
				if (this.currentQuestionIndex < 72) {
					this.answer[this.currentQuestionIndex] =
						"lb" +
						item.lbassessment_id +
						"-" +
						item.subjectid +
						"=" +
						item.id;
					console.log("当前答案:", this.answer);
				} else {
					this.answer[this.currentQuestionIndex] =
						item.id + "=" +
						item.name
					console.log("当前答案:", this.answer);
				}

				// 选择答案后保存进度
				this.saveProgress();

				// 禁止选择一段时间
				this.canSelect = false;
				setTimeout(() => {
					this.canSelect = true;
					if (this.currentQuestionIndex < this.subjectList.length - 1) {
						this.nextQuestion(); // 自动进入下一题
					}
				}, 200);
			},
			isSelected(optionIndex) {
				const options = this.selectedOptions[this.currentQuestionIndex];
				return options && options.includes(optionIndex);
			},
			gobake() {
				// 返回前保存进度
				this.saveProgress();
				uni.navigateBack()
			},
			clearCurrentSelection() {
				this.selectedOptions.splice(this.currentQuestionIndex, 1);
			},
			submit() {
				uni.showLoading({
					title: "正在提交"
				})

				let data = {
					answer: this.answer,
					userid: uni.getStorageSync("userinfo").id,
					starttime: this.starttime
				}
				saveAnswer(data).then(res => {
					uni.hideLoading()
					if (res.state === "ok") {
						console.log("提交成功:", this.subjectId, this.reportId);
						// 提交成功后清除保存的进度
						uni.removeStorageSync("answerProgressData");
						uni.showModal({
							title: "感谢您的作答",
							showCancel: false, // 不显示取消按钮
							confirmText: "确定",
							success(res) {
								uni.removeStorageSync("answerProgressData");
								uni.navigateBack()
							}
						})
					}
				}).catch(err => {
					uni.hideLoading();
					console.error("提交失败:", err);
				})
			}

		},
	}
</script>

<style lang="scss">
	/* 样式保持不变 */
	.van-slider__button {
		background-image: url("https://lesson.iapeap.com/images/sleep/jindu.png");
		background-size: 100% 100%;
		width: 35rpx !important;
		height: 35rpx !important;
	}

	.tjcg {
		width: 100%;
		height: 100vh;
		position: absolute;
		top: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		background: rgba(57, 57, 57, 0.6);
		z-index: 999;

		.gobaogao {
			width: 75%;
			height: 15%;
			position: relative;
			top: 68%;
			left: 13%;
		}

		.tjimg {
			width: 80%;
			height: 40%;
			background-image: url("https://lesson.iapeap.com/images/tijiaochenggongbaogao.png");
			background-size: 100% 100%;
		}
	}

	.van-slider {
		background-color: #C6DBF1 !important;
	}

	.slider {
		padding: 10rpx;
		border-radius: 25rpx;
	}

	.content {
		height: 100vh;
		width: 100%;
		// padding-bottom: 250rpx;
	}

	.box {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
	}

	.bgfilter {
		width: 100%;
		height: 658rpx;
		filter: blur(7px);
		position: relative;
		top: 0;
		z-index: 0;
	}

	.navigateBack {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 100rpx 40rpx 0rpx 40rpx;
		box-sizing: border-box;
		color: #38659C;
	}

	.answer_timu {
		width: 672rpx;
		height: 176rpx;
		background: #E3EFFC;
		box-shadow: 0rpx 8rpx 14rpx 0rpx #DFE9F3, inset 0rpx 0rpx 6rpx 2rpx #FFFFFF;
		border-radius: 32rpx;
		backdrop-filter: blur(5px);
		margin: 0 auto;
		margin-top: 50rpx;
		padding: 30rpx 40rpx;
		box-sizing: border-box;
		font-weight: 500;
		font-size: 30rpx;
		color: #0B4197;

		.timu_title {
			margin-bottom: 20rpx;
			display: flex;
			justify-content: space-between;
		}
	}

	.answer_daan {
		width: 672rpx;
		min-height: 500rpx;
		background: #E3EFFC;
		box-shadow: 0rpx 8rpx 14rpx 0rpx #DFE9F3, inset 0rpx 0rpx 6rpx 2rpx #FFFFFF;
		backdrop-filter: blur(5px);
		border-radius: 32rpx;
		margin: 0 auto;
		margin-top: -30rpx;
		padding: 78rpx 54rpx 40rpx 54rpx;
		box-sizing: border-box;

		.xiaobiaoti {
			font-weight: 500;
			font-size: 28rpx;
			color: #000025;
			line-height: 40rpx;
			letter-spacing: 1px;
			text-align: left;
			font-style: normal;
		}
	}

	.suozhen {
		width: 334rpx;
		height: 58rpx;
		position: relative;
		z-index: 999;
		left: calc(50% - 167rpx);
		margin-top: -58rpx;
		top: 4rpx;
	}

	.options {
		margin-top: 40rpx;

		.options_item {
			width: 536rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 4rpx 16rpx 0rpx rgba(185, 184, 184, 0.5);
			border-radius: 16rpx;
			box-sizing: border-box;
			padding: 0 40rpx;
			line-height: 80rpx;
			font-weight: 500;
			font-size: 26rpx;
			color: #000025;
			margin-top: 48rpx;
		}

		.options_item2 {
			background: #AFC5E0;
			box-shadow: 0rpx 4rpx 16rpx 0rpx #AFC5E0;
			color: #6F7E91;
		}

		.options_item3 {
			background: #72ACF4;
			box-shadow: 0rpx 4rpx 16rpx 0rpx #8CB0DC;
			color: #fff;
		}
	}

	.optionscat {
		width: 212rpx;
		height: 100rpx;
		position: relative;
		left: calc(100% - 185rpx);
		top: 40rpx;
	}

	.test_btn {
		display: flex;
		justify-content: center;
		margin-top: 50rpx;

		.btnimg {
			width: 364rpx;
			height: 106rpx;
		}
	}
</style>